<template>
  <div class="resource-catalog-v2">
    <div class="catalog-layout">
      <!-- 左侧资源树 -->
      <div class="catalog-sidebar">
        <div class="sidebar-header">
          <div class="header-content">
            <h3>资源目录</h3>
            <a-button
              type="text"
              size="small"
              @click="useMenuMode = !useMenuMode"
              :title="useMenuMode ? '切换到树形模式' : '切换到菜单模式'"
              class="mode-toggle-btn"
            >
              <IconifyIcon
                :icon="
                  useMenuMode
                    ? 'ant-design:branches-outlined'
                    : 'ant-design:menu-outlined'
                "
              />
            </a-button>
          </div>
        </div>

        <!-- 分类标签页 -->
        <a-tabs v-model="activeCategory">
          <a-tab-pane key="all" tab="全部">
            <div class="tree-container">
              <a-input-search
                v-model:value="searchKeyword"
                placeholder="搜索资源..."
                @search="handleTreeSearch"
                allow-clear
              />
              <ResourceTree
                v-if="!useMenuMode"
                :tree-data="resourceTree"
                :expanded-keys="expandedKeys"
                :selected-resource-id="selectedResourceId"
                :resource-type-config="resourceTypeConfig"
                @update:selected-resource-id="handleTreeSelect"
                @expand-change="handleTreeExpand"
                @create-resource="handleCreateResource"
                @create-sub-resource="handleCreateSubResource"
                @edit-resource="handleEditResource"
                @delete-resource="handleDeleteResource"
              />
              <ResourceMenu
                v-else
                :tree-data="resourceTree"
                :selected-resource-id="selectedResourceId"
                :resource-type-config="resourceTypeConfig"
                @update:selected-resource-id="handleTreeSelect"
                @create-resource="handleCreateResource"
                @create-sub-resource="handleCreateSubResource"
                @edit-resource="handleEditResource"
                @delete-resource="handleDeleteResource"
              />
            </div>
          </a-tab-pane>

          <a-tab-pane key="type" tab="按类型">
            <div class="tree-container">
              <a-tree
                :tree-data="typeTree"
                :expanded-keys="expandedKeys"
                :selected-keys="selectedKeys"
                :show-line="false"
                @expand="handleTreeExpand"
                @select="handleTypeTreeSelect"
              >
                <template #title="{ title, key, children }">
                  <span class="tree-node">
                    <IconifyIcon
                      :icon="getResourceTypeIcon(key)"
                      class="node-icon"
                    />
                    <span class="node-title">{{ title }}</span>
                    <span
                      v-if="children && children.length > 0"
                      class="node-count"
                    >
                      ({{ children.length }})
                    </span>
                  </span>
                </template>
              </a-tree>
            </div>
          </a-tab-pane>

          <a-tab-pane key="business" tab="按业务">
            <div class="tree-container">
              <a-tree
                :tree-data="businessTree"
                :expanded-keys="expandedKeys"
                :selected-keys="selectedKeys"
                :show-line="false"
                @expand="handleTreeExpand"
                @select="handleBusinessTreeSelect"
              />
            </div>
          </a-tab-pane>

          <a-tab-pane key="custom" tab="自定义">
            <div class="custom-tags">
              <a-tag
                v-for="tag in customTags"
                :key="tag.key"
                :color="tag.color"
                @click="handleCustomTagClick(tag)"
              >
                {{ tag.label }} ({{ tag.count }})
              </a-tag>
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>

      <!-- 中间主内容区域 -->
      <div class="catalog-main">
        <!-- 工具栏 -->
        <div class="toolbar">
          <div class="toolbar-left">
            <h2>{{ getListTitle() }}</h2>
            <span class="total-count">共 {{ totalCount }} 项</span>
          </div>
          <div class="toolbar-right">
            <a-space>
              <a-button @click="handleBatchImport"> 批量导入 </a-button>
              <a-button type="primary" @click="handleCreateResource">
                新建资源
              </a-button>
              <a-button
                v-if="detailVisible && selectedResource"
                type="text"
                @click="toggleFullscreen"
                :title="isFullscreen ? '退出全屏' : '全屏显示'"
              >
                <IconifyIcon
                  :icon="
                    isFullscreen
                      ? 'ant-design:fullscreen-exit-outlined'
                      : 'ant-design:fullscreen-outlined'
                  "
                />
              </a-button>
            </a-space>
          </div>
        </div>

        <!-- 动态内容区域 -->
        <div class="content-container">
          <!-- 显示列表 -->
          <div
            v-if="tableData.length > 0 && !detailVisible"
            class="table-container"
          >
            <div class="table-toolbar">
              <a-space>
                <a-input-search
                  v-model:value="searchValue"
                  placeholder="搜索资源..."
                  @search="handleSearch"
                  style="width: 200px"
                />
                <a-select
                  v-model:value="filterType"
                  placeholder="资源类型"
                  style="width: 120px"
                  @change="handleFilterChange"
                >
                  <a-select-option value="">全部类型</a-select-option>
                  <a-select-option value="PHYSICAL">物理资源</a-select-option>
                  <a-select-option value="VIRTUAL">虚拟资源</a-select-option>
                  <a-select-option value="SERVICE">服务资源</a-select-option>
                </a-select>
                <a-select
                  v-model:value="filterStatus"
                  placeholder="状态"
                  style="width: 100px"
                  @change="handleFilterChange"
                >
                  <a-select-option value="">全部状态</a-select-option>
                  <a-select-option value="ACTIVE">正常</a-select-option>
                  <a-select-option value="INACTIVE">停用</a-select-option>
                  <a-select-option value="MAINTENANCE">维护中</a-select-option>
                </a-select>
              </a-space>
            </div>

            <a-table
              :data-source="tableData"
              :columns="tableColumns"
              :loading="tableLoading"
              :pagination="pagination"
              :row-key="(record) => record.id"
              @change="handleTableChange"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'action'">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleView(record)"
                    >
                      查看
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleEdit(record)"
                    >
                      编辑
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="handleDelete(record)"
                    >
                      删除
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </div>

          <!-- 无子节点时显示详情 -->
          <div
            v-else-if="detailVisible && selectedResource"
            class="detail-container"
            :class="{ 'fullscreen-mode': isFullscreen }"
          >
            <!-- 全屏模式下的退出按钮 -->
            <div v-if="isFullscreen" class="fullscreen-exit-btn">
              <a-button type="text" @click="toggleFullscreen" size="large">
                <IconifyIcon icon="ant-design:fullscreen-exit-outlined" />
              </a-button>
            </div>
            <div class="detail-content">
              <!-- 原有的资源管理组件 -->
              <ResourceSelfManagement
                :resource="selectedResource"
                @edit-capability="handleEditCapability"
                @capability-update="handleCapabilityUpdate"
              />
            </div>
          </div>

          <!-- 默认状态 -->
          <div v-else class="empty-container">
            <a-empty description="请选择左侧资源节点查看详情" />
          </div>
        </div>
      </div>
    </div>

    <!-- 资源详情抽屉 -->
    <a-drawer
      v-model:open="drawerVisible"
      :title="drawerTitle"
      placement="right"
      :width="drawerWidth"
      @close="closeDetail"
    >
      <div class="drawer-content">
        <!-- 原有的资源管理组件 -->
        <ResourceSelfManagement
          :resource="selectedResource"
          @edit-capability="handleEditCapability"
          @capability-update="handleCapabilityUpdate"
        />
      </div>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
import { message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';
import { getResources } from '#/api/resource-center';
import { ResourceTree, ResourceMenu } from '../components';
import ResourceSelfManagement from '../components/ResourceSelfManagement.vue';

// 响应式数据
const activeCategory = ref('all');
const searchKeyword = ref('');
const searchValue = ref('');
const filterType = ref('');
const filterBusiness = ref('');
const filterStatus = ref('');
const treeLoading = ref(false);
const tableLoading = ref(false);
const detailVisible = ref(false);
const detailActiveTab = ref('basic');
const drawerVisible = ref(false);
const drawerWidth = ref('70%');
const drawerTitle = ref('资源详情');
const isFullscreen = ref(false);
const useMenuMode = ref(true); // 默认使用Menu模式

// 树形数据
const resourceTree = ref<any[]>([]);
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const selectedResource = ref<any>(null);
const selectedResourceId = ref<string | null>(null);

// 资源类型配置
const resourceTypeConfig = ref<Record<string, any>>({
  // 基础资源类型
  DIGITAL: { icon: 'ant-design:laptop-outlined', color: '#1890ff' },
  HUMAN: { icon: 'ant-design:user-outlined', color: '#52c41a' },
  PHYSICAL: { icon: 'ant-design:tool-outlined', color: '#faad14' },
  SERVICE: { icon: 'ant-design:customer-service-outlined', color: '#722ed1' },
  VIRTUAL: { icon: 'ant-design:cloud-outlined', color: '#13c2c2' },

  // 业务类型
  HOTEL: { icon: 'ant-design:home-outlined', color: '#1890ff' },
  APARTMENT: { icon: 'ant-design:bank-outlined', color: '#52c41a' },
  HOT_SPRING: { icon: 'ant-design:fire-outlined', color: '#fa541c' },
  MEDICAL_BEAUTY: {
    icon: 'ant-design:medicine-box-outlined',
    color: '#eb2f96',
  },
  PET_MEDICAL: { icon: 'ant-design:heart-outlined', color: '#f5222d' },
  RESTAURANT: { icon: 'ant-design:coffee-outlined', color: '#fa8c16' },
  TRAINING: { icon: 'ant-design:book-outlined', color: '#722ed1' },
  OTHER: { icon: 'ant-design:appstore-outlined', color: '#666' },

  // 子类型
  room: { icon: 'ant-design:appstore-outlined', color: '#52c41a' },
  facility: { icon: 'ant-design:tool-outlined', color: '#722ed1' },
  equipment: { icon: 'ant-design:setting-outlined', color: '#13c2c2' },
  staff: { icon: 'ant-design:team-outlined', color: '#faad14' },

  // 默认配置
  default: { icon: 'ant-design:file-outlined', color: '#666' },
});

// 表格数据
const tableData = ref<any[]>([]);
const totalCount = ref(0);
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

// 自定义标签
const customTags = ref([
  { key: 'hot', label: '热门', color: 'red', count: 0 },
  { key: 'new', label: '新增', color: 'green', count: 0 },
  { key: 'maintenance', label: '维护中', color: 'orange', count: 0 },
  { key: 'offline', label: '已下线', color: 'gray', count: 0 },
]);

// 计算属性
const typeTree = computed(() => {
  return buildTypeTree(resourceTree.value);
});

const businessTree = computed(() => {
  return buildBusinessTree(resourceTree.value);
});

// 表格列配置
const tableColumns = [
  { title: '资源名称', dataIndex: 'name', key: 'name', width: 200 },
  { title: '资源编码', dataIndex: 'code', key: 'code', width: 150 },
  {
    title: '资源类型',
    dataIndex: 'resource_type',
    key: 'resource_type',
    width: 120,
  },
  {
    title: '业务类型',
    dataIndex: 'business_type',
    key: 'business_type',
    width: 120,
  },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  {
    title: '创建时间',
    dataIndex: 'create_time',
    key: 'create_time',
    width: 180,
  },
  { title: '操作', key: 'action', width: 200 },
];

// 初始化
onMounted(() => {
  console.log('页面初始化开始');
  loadResourceTree();
  loadTableData();
});

// 加载资源树
const loadResourceTree = async () => {
  try {
    treeLoading.value = true;
    const result = await getResources({ pageSize: 1000 });
    console.log('资源树数据:', result);

    // 处理API返回的数据格式
    let items = [];
    if (result && result.data && result.data.items) {
      items = result.data.items;
    } else if (result && result.items) {
      items = result.items;
    } else {
      console.error('资源树数据格式错误:', result);
      message.error('资源树数据格式错误');
      return;
    }

    if (items.length > 0) {
      resourceTree.value = buildResourceTree(items);
      updateCustomTagCounts();
    } else {
      console.warn('没有找到资源数据');
      resourceTree.value = [];
    }
  } catch (error) {
    console.error('加载资源树失败:', error);
    message.error('加载资源树失败');
  } finally {
    treeLoading.value = false;
  }
};

// 加载表格数据
const loadTableData = async () => {
  try {
    tableLoading.value = true;
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchValue.value,
      resource_type: filterType.value,
      business_type: filterBusiness.value,
      status: filterStatus.value,
    };
    const result = await getResources(params);
    console.log('表格数据:', result);

    // 处理API返回的数据格式
    let items = [];
    let total = 0;

    if (result && result.data && result.data.items) {
      items = result.data.items;
      total = result.data.total;
    } else if (result && result.items) {
      items = result.items;
      total = result.total;
    } else {
      console.error('表格数据格式错误:', result);
      message.error('表格数据格式错误');
      return;
    }

    tableData.value = items;
    pagination.total = total;
    totalCount.value = total;
  } catch (error) {
    console.error('加载表格数据失败:', error);
    message.error('加载表格数据失败');
  } finally {
    tableLoading.value = false;
  }
};

// 构建资源树
const buildResourceTree = (resources: any[]): any[] => {
  const treeMap = new Map<string, any>();
  const rootNodes: any[] = [];

  resources.forEach((resource) => {
    treeMap.set(resource.id, {
      key: `resource-${resource.id}`,
      title: resource.name,
      children: [],
      data: resource,
      // 直接使用资源数据中的icon和color
      icon: resource.icon || 'ant-design:file-outlined',
      color: resource.color || '#666',
      resource_type: resource.resource_type,
    });
  });

  resources.forEach((resource) => {
    const node = treeMap.get(resource.id)!;
    if (resource.parent_id) {
      const parent = treeMap.get(resource.parent_id);
      if (parent) {
        parent.children.push(node);
      }
    } else {
      rootNodes.push(node);
    }
  });

  return rootNodes;
};

// 构建类型树
const buildTypeTree = (tree: any[]): any[] => {
  const typeMap = new Map<string, any>();

  const traverse = (nodes: any[]) => {
    nodes.forEach((node) => {
      const type = node.data?.resource_type || '未知类型';
      if (!typeMap.has(type)) {
        const typeConfig =
          resourceTypeConfig.value[type] || resourceTypeConfig.value.default;
        typeMap.set(type, {
          key: `type_${type}`,
          title: type,
          children: [],
          data: {
            id: `type_${type}`,
            name: type,
            code: type,
            resource_type: type,
            business_type: 'OTHER',
            status: 'ACTIVE',
            create_time: new Date().toISOString(),
            update_time: new Date().toISOString(),
          },
          // 为ResourceTree组件添加必要的字段
          icon: typeConfig.icon,
          color: typeConfig.color,
          resource_type: type,
        });
      }
      typeMap.get(type)!.children.push(node);
    });
  };

  traverse(tree);
  return Array.from(typeMap.values());
};

// 构建业务树
const buildBusinessTree = (tree: any[]): any[] => {
  const businessMap = new Map<string, any>();

  const traverse = (nodes: any[]) => {
    nodes.forEach((node) => {
      const business = node.data?.business_type || '未知业务';
      if (!businessMap.has(business)) {
        businessMap.set(business, {
          key: `business_${business}`,
          title: business,
          children: [],
          data: {
            id: `business_${business}`,
            name: business,
            code: business,
            resource_type: 'OTHER',
            business_type: business,
            status: 'ACTIVE',
            create_time: new Date().toISOString(),
            update_time: new Date().toISOString(),
          },
          // 为ResourceTree组件添加必要的字段
          icon: 'ant-design:bank-outlined',
          color: '#52c41a',
          resource_type: 'business',
        });
      }
      businessMap.get(business)!.children.push(node);
    });
  };

  traverse(tree);
  return Array.from(businessMap.values());
};

// 更新自定义标签计数
const updateCustomTagCounts = () => {
  const resources = flattenTree(resourceTree.value);
  if (customTags.value[0]) {
    customTags.value[0].count = resources.filter(
      (r: any) => r?.status === 'ACTIVE',
    ).length;
  }
  if (customTags.value[1]) {
    customTags.value[1].count = resources.filter(
      (r: any) =>
        r?.create_time &&
        new Date(r.create_time).getTime() >
          Date.now() - 7 * 24 * 60 * 60 * 1000,
    ).length;
  }
  if (customTags.value[2]) {
    customTags.value[2].count = resources.filter(
      (r: any) => r?.status === 'MAINTENANCE',
    ).length;
  }
  if (customTags.value[3]) {
    customTags.value[3].count = resources.filter(
      (r: any) => r?.status === 'INACTIVE',
    ).length;
  }
};

// 扁平化树结构
const flattenTree = (tree: any[]): any[] => {
  const result: any[] = [];
  const traverse = (nodes: any[]) => {
    nodes.forEach((node) => {
      if (node.data) {
        result.push(node.data);
      }
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };
  traverse(tree);
  return result;
};

// 事件处理函数
const handleCategoryChange = (key: string) => {
  activeCategory.value = key;
  selectedKeys.value = [];
};

const handleTreeSearch = (value: string) => {
  searchKeyword.value = value;
};

const handleTreeExpand = (keys: string[]) => {
  expandedKeys.value = keys;
};

const handleTreeSelect = (resourceId: string) => {
  selectedResourceId.value = resourceId;
  selectedKeys.value = [`resource-${resourceId}`];

  const resource = findResourceInTree(
    resourceTree.value,
    `resource-${resourceId}`,
  );
  if (resource) {
    selectedResource.value = resource;
    // 先设置为列表模式，然后加载数据
    detailVisible.value = false;

    // 加载该资源的子资源列表
    loadChildrenResources(resourceId).then((hasChildren) => {
      if (hasChildren) {
        // 有子节点：保持列表模式，数据已经在loadChildrenResources中设置
      } else {
        // 无子节点：切换到详情模式
        detailVisible.value = true;
        tableData.value = [];
        totalCount.value = 0;
      }
    });
  }
};

const handleTypeTreeSelect = (keys: string[]) => {
  selectedKeys.value = keys;
  if (keys.length > 0) {
    const typeKey = keys[0];
    if (typeKey) {
      const type = typeKey.replace('type_', '');
      filterType.value = type;
      filterBusiness.value = '';
      // 重置分页
      pagination.current = 1;
      // 清空详情显示
      detailVisible.value = false;
      selectedResource.value = null;
      loadTableData();
    }
  }
};

const handleBusinessTreeSelect = (keys: string[]) => {
  selectedKeys.value = keys;
  if (keys.length > 0) {
    const businessKey = keys[0];
    if (businessKey) {
      const business = businessKey.replace('business_', '');
      // 设置业务类型过滤
      filterType.value = '';
      filterBusiness.value = business;
      // 重置分页
      pagination.current = 1;
      // 清空详情显示
      detailVisible.value = false;
      selectedResource.value = null;
      loadTableData();
    }
  }
};

const handleCustomTagClick = (tag: any) => {
  // 根据标签类型设置过滤条件
  switch (tag.key) {
    case 'hot':
      filterType.value = '';
      filterBusiness.value = '';
      filterStatus.value = 'ACTIVE';
      break;
    case 'new':
      filterType.value = '';
      filterBusiness.value = '';
      filterStatus.value = 'ACTIVE';
      break;
    case 'maintenance':
      filterType.value = '';
      filterBusiness.value = '';
      filterStatus.value = 'MAINTENANCE';
      break;
    case 'offline':
      filterType.value = '';
      filterBusiness.value = '';
      filterStatus.value = 'INACTIVE';
      break;
    default:
      filterType.value = '';
      filterBusiness.value = '';
      filterStatus.value = '';
  }
  // 重置分页
  pagination.current = 1;
  // 清空详情显示
  detailVisible.value = false;
  selectedResource.value = null;
  loadTableData();
};

const handleSearch = () => {
  pagination.current = 1;
  loadTableData();
};

const handleFilterChange = () => {
  pagination.current = 1;
  loadTableData();
};

const handleTableChange = (paginationInfo: any, filters: any, sorter: any) => {
  pagination.current = paginationInfo.current;
  pagination.pageSize = paginationInfo.pageSize;
  loadTableData();
};

const handleView = (row: any) => {
  selectedResource.value = row;
  detailActiveTab.value = 'basic';
  // 显示抽屉
  drawerVisible.value = true;
};

const handleEdit = (row: any) => {
  selectedResource.value = row;
  detailActiveTab.value = 'basic';
  message.info('编辑功能待实现');
};

const handleDelete = (row: any) => {
  selectedResource.value = row;
  message.info('删除功能待实现');
};

const handleCreateResource = () => {
  message.info('新建资源功能待实现');
};

const handleCreateSubResource = (parentId: string) => {
  message.info(`为资源 ${parentId} 创建子资源功能待实现`);
};

const handleEditResource = (resourceId: string) => {
  message.info(`编辑资源 ${resourceId} 功能待实现`);
};

const handleDeleteResource = (resourceId: string) => {
  message.info(`删除资源 ${resourceId} 功能待实现`);
};

// 全屏切换函数
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value;
};

// ESC键退出全屏
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape' && isFullscreen.value) {
    isFullscreen.value = false;
  }
};

// 监听键盘事件
onMounted(() => {
  document.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
});

// 获取资源类型颜色
const getResourceTypeColor = (type: string) => {
  const typeConfig = resourceTypeConfig.value[type];
  return typeConfig?.color || '#666';
};

// 获取资源类型标签
const getResourceTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    DIGITAL: '数字资源',
    HUMAN: '人力资源',
    PHYSICAL: '物理资源',
    SERVICE: '服务资源',
    VIRTUAL: '虚拟资源',
    HOTEL: '酒店',
    APARTMENT: '公寓',
    HOT_SPRING: '温泉洗浴',
    MEDICAL_BEAUTY: '医美',
    PET_MEDICAL: '宠物医疗',
    RESTAURANT: '餐饮',
    TRAINING: '培训班',
    OTHER: '其他',
  };
  return typeMap[type] || type || '未知类型';
};

const handleBatchImport = () => {
  message.info('批量导入功能待实现');
};

const closeDetail = () => {
  // 只关闭抽屉，不影响中间区域的详情显示
  drawerVisible.value = false;
};

// 处理能力编辑
const handleEditCapability = (capabilityKey: string) => {
  console.log('编辑能力:', capabilityKey);
  message.info(`编辑能力: ${capabilityKey}`);
};

// 处理能力更新
const handleCapabilityUpdate = (capabilities: any) => {
  console.log('能力更新:', capabilities);

  // 更新当前选中资源的能力配置
  if (selectedResource.value) {
    selectedResource.value = {
      ...selectedResource.value,
      capabilities: JSON.stringify(capabilities),
    };
  }

  message.success('能力配置已更新');
};

// 属性管理相关函数
const handleEditProperties = () => {
  message.info('属性管理功能待实现');
};

const handleEditPropertyData = () => {
  message.info('属性数据编辑功能待实现');
};

// 能力管理相关函数
const handleShowCapabilityGuide = () => {
  message.info('能力使用指南功能待实现');
};

const handleEditCapabilities = () => {
  message.info('添加能力功能待实现');
};

// 交易管理相关函数
const handleShowTradingGuide = () => {
  message.info('交易指南功能待实现');
};

const handleConfigureTrading = () => {
  message.info('配置交易功能待实现');
};

const loadChildrenResources = async (parentId: string) => {
  try {
    const result = await getResources({ parent_id: parentId, pageSize: 100 });

    // 处理API返回的数据格式
    let items = [];
    let total = 0;

    if (result && result.data && result.data.items) {
      items = result.data.items;
      total = result.data.total;
    } else if (result && result.items) {
      items = result.items;
      total = result.total;
    } else {
      console.warn('没有找到子资源数据');
      items = [];
      total = 0;
    }

    tableData.value = items;
    totalCount.value = total;

    // 返回是否有子节点
    return items.length > 0;
  } catch (error) {
    console.error('加载子资源失败:', error);
    message.error('加载子资源失败');
    return false;
  }
};

const getListTitle = () => {
  if (selectedResource.value) {
    if (detailVisible.value) {
      return `${selectedResource.value.name} - 详情`;
    } else {
      return `${selectedResource.value.name} - 子资源`;
    }
  }
  return '资源列表';
};

const formatDateTime = (dateTime?: string) => {
  if (!dateTime) return '-';
  return new Date(dateTime).toLocaleString('zh-CN');
};

const formatJson = (obj: any) => {
  if (!obj) return '暂无数据';
  try {
    return JSON.stringify(obj, null, 2);
  } catch (error) {
    return String(obj);
  }
};

const findResourceInTree = (tree: any[], key: string): any => {
  for (const node of tree) {
    if (node.key === key && node.data) {
      return node.data;
    }
    if (node.children.length > 0) {
      const found = findResourceInTree(node.children, key);
      if (found) return found;
    }
  }
  return null;
};

// 图标函数
const getResourceIcon = (key: string) => {
  // 从资源树中查找对应的资源数据
  const resource = findResourceInTree(resourceTree.value, key);
  if (resource && resource.icon) {
    return resource.icon;
  }
  return 'mdi:cube-outline';
};

const getResourceTypeIcon = (key: string) => {
  const type = key.replace('type_', '');
  switch (type) {
    case 'PHYSICAL':
      return 'mdi:cube';
    case 'VIRTUAL':
      return 'mdi:cloud';
    case 'SERVICE':
      return 'mdi:cog';
    case 'DIGITAL':
      return 'mdi:laptop';
    case 'HUMAN':
      return 'mdi:account-group';
    default:
      return 'mdi:cube-outline';
  }
};

const getBusinessTypeIcon = (key: string) => {
  const business = key.replace('business_', '');
  switch (business) {
    case 'HOTEL':
      return 'mdi:bed';
    case 'CAR_RENTAL':
      return 'mdi:car';
    case 'APARTMENT':
      return 'mdi:home';
    case 'SPA':
      return 'mdi:heart';
    case 'SCENIC':
      return 'mdi:tree';
    case 'RESTAURANT':
      return 'mdi:food';
    case 'MEDICAL_BEAUTY':
      return 'mdi:medical-bag';
    case 'BEAUTY_SALON':
      return 'mdi:scissors-cutting';
    default:
      return 'mdi:briefcase';
  }
};
</script>

<style lang="less" scoped>
.resource-catalog-v2 {
  height: 100%;

  .catalog-layout {
    display: flex;
    height: 100%;
    gap: 16px;
    padding: 10px;
  }

  .catalog-sidebar {
    width: 320px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 7px;
    .sidebar-header {
      padding: 16px 20px;
      border-bottom: 1px solid #f0f0f0;

      .header-content {
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 600;
        }

        .mode-toggle-btn {
          width: 32px;
          height: 32px;
          padding: 0;
          border: none;
          background: transparent;
          color: #8c8c8c;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 4px;
          transition: all 0.2s ease;

          &:hover {
            color: #1890ff;
            background: #f0f8ff;
          }
        }
      }
    }

    .tree-container {
      padding: 16px 20px;

      .ant-tree {
        .ant-tree-node-content-wrapper {
          padding: 4px 8px;
          margin: 2px 0;
        }

        .tree-node {
          display: flex;
          align-items: center;
          gap: 8px;
          width: 100%;

          .node-icon {
            font-size: 16px;
            color: #666;
            flex-shrink: 0;
          }

          .node-title {
            flex: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .node-count {
            color: #999;
            font-size: 12px;
            flex-shrink: 0;
          }
        }
      }
    }

    .custom-tags {
      padding: 16px 20px;

      .ant-tag {
        margin-bottom: 8px;
        margin-right: 8px;
        cursor: pointer;
        padding: 4px 8px;
      }
    }
  }

  .catalog-main {
    flex: 1;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;

    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      border-bottom: 1px solid #f0f0f0;

      .toolbar-left {
        display: flex;
        align-items: center;
        gap: 12px;

        h2 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
        }

        .total-count {
          color: #666;
          font-size: 14px;
        }
      }
    }

    .content-container {
      flex: 1;
      padding: 0 10px;
      overflow: auto;

      .table-container {
        .table-toolbar {
          margin-bottom: 16px;
        }
      }

      .detail-container {
        position: relative;
        transition: all 0.3s ease;

        &.fullscreen-mode {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 1000;
          background: #fff;
          border-radius: 0;
          box-shadow: none;
          margin: 0;
          padding: 0;

          .fullscreen-exit-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1002;

            .ant-btn {
              width: 40px;
              height: 40px;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              background: rgba(255, 255, 255, 0.9);
              backdrop-filter: blur(10px);
              border: 1px solid rgba(0, 0, 0, 0.1);
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

              &:hover {
                background: rgba(255, 255, 255, 1);
                transform: scale(1.1);
              }
            }
          }

          .detail-content {
            height: 100vh;
            overflow-y: auto;
            padding: 20px;
          }
        }

        .detail-content {
          // padding: 24px;paddingpadding

          .json-display {
            background: #f5f5f5;
            padding: 12px;
            border-radius: 4px;
            font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
            font-size: 12px;
            line-height: 1.5;
            white-space: pre-wrap;
            word-break: break-all;
            max-height: 300px;
            overflow-y: auto;
          }
        }
      }

      .empty-container {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 400px;
      }
    }
  }

  .drawer-content {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }

    .json-display {
      background: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
      font-size: 12px;
      line-height: 1.5;
      white-space: pre-wrap;
      word-break: break-all;
      max-height: 300px;
      overflow-y: auto;
    }
  }
}
</style>
